package com.banshuibao.bsb_android.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.AuthorizedResultModel;
import com.banshuibao.bsb_android.model.ExpertAnswerDetailModel;
import com.banshuibao.bsb_android.model.ExpertResultModel;
import com.banshuibao.bsb_android.model.RequestAuthorizedModel;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.MediaPlayerUtil;
import com.banshuibao.bsb_android.util.ParamsUtil;
import com.banshuibao.bsb_android.util.QuickDoubleClickable;
import com.banshuibao.bsb_android.util.TimeUtil;
import com.cunoraz.gifview.library.GifView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangpan on 2018/1/3.
 */

public class HomeAnswerListenRecordAdapter extends RecyclerView.Adapter<HomeAnswerListenRecordAdapter.ViewHolder> implements MediaPlayerUtil.MediaPlayerPlayingListener {

    private Activity context;
    private List<ExpertAnswerDetailModel.DataBean.VoicesBean> list;
    private MediaPlayerUtil mediaPlayerUtil;
    private MediaPlayer media;
    private String time;
    private PopupWindow popupWindow;
    private String questionUuid;
    private ExpertResultModel.DataBean dataBean;
    private String voiceName, voiceContent;

    private Handler handler = new Handler() {
        TextView textView;
        ViewHolder holder;
        private boolean stop = false;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (holder == null || media == null)
                return;
            switch (msg.what) {
                case 0:
                    if (!stop) {
                        sendEmptyMessageDelayed(0, 1000);
                        textView.setText(ParamsUtil.millsecondsToStr(media.getDuration() - media.getCurrentPosition()));
                        holder.relativeLayout.setEnabled(false);
                        holder.show_iv.setVisibility(View.GONE);
                        holder.gifView.setVisibility(View.VISIBLE);
                    }
                    break;
                case 1:
                    holder = (ViewHolder) msg.obj;
                    textView = holder.text_tv;
                    stop = false;
                    holder.relativeLayout.setEnabled(false);
                    break;
                case 2:
                    stop = true;
                    holder.show_iv.setVisibility(View.VISIBLE);
                    holder.gifView.setVisibility(View.GONE);
                    holder.relativeLayout.setEnabled(true);
                    holder.relativeLayout.setBackground(context.getResources().getDrawable(R.drawable.listenback));
                    textView.setText(time);
                    media.pause();
                    media.stop();
                    media.reset();
                    break;
            }
        }
    };

    public HomeAnswerListenRecordAdapter(Activity context, MediaPlayerUtil mediaPlayerUtil) {
        this.context = context;
        list = new ArrayList<>();
        this.mediaPlayerUtil = mediaPlayerUtil;
        mediaPlayerUtil.setOnMediaPlayerPlayingListener(this);
    }

    public void setData(List<ExpertAnswerDetailModel.DataBean.VoicesBean> voicesBean, ExpertResultModel.DataBean dataBean) {
        if (this.list != null) {
            this.list.clear();
            this.list.addAll(voicesBean);
            this.dataBean = dataBean;
            this.questionUuid = dataBean.getUuid();
            notifyDataSetChanged();
        }
    }

    @Override
    public HomeAnswerListenRecordAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.recorder_list_layout, null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final HomeAnswerListenRecordAdapter.ViewHolder holder, final int position) {
        final ExpertAnswerDetailModel.DataBean.VoicesBean expertVoicesBean = list.get(position);
        if (expertVoicesBean != null) {
            final String uuid = expertVoicesBean.getUuid();
            final long voiceTime = expertVoicesBean.getVoiceTime();
            final String during = TimeUtil.formatDuring(voiceTime);
            holder.text_tv.setText(during);

            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //审请权限
                    getAuthorized(questionUuid, uuid, during, holder, "voice");
                }
            });
            holder.show_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //审请权限
                    getAuthorized(questionUuid, uuid, during, holder, "text");
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return list != null ? list.size() : 0;
    }

    @Override
    public void OnError(MediaPlayer mediaPlayer) {

    }

    @Override
    public void OnPrepared(MediaPlayer mediaPlayer) {
        //开始播放
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            handler.sendEmptyMessageDelayed(0, 1000);
        }
    }

    @Override
    public void OnCompletion(MediaPlayer mediaPlayer) {
        stopMedia();
    }

    public void stopMedia() {
        handler.sendEmptyMessage(2);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout relativeLayout;
        TextView text_tv;
        ImageView show_iv;
        TextView show_tv;
        GifView gifView;

        public ViewHolder(View itemView) {
            super(itemView);
            relativeLayout = itemView.findViewById(R.id.play);
            text_tv = itemView.findViewById(R.id.text_tv);
            show_iv = itemView.findViewById(R.id.voice_iv);
            gifView = itemView.findViewById(R.id.voice_gif);
            show_tv = itemView.findViewById(R.id.show_tv);
            gifView.setGifResource(R.raw.play);
        }
    }

    /**
     * 播放语音
     */
    private void playAudio(String name) {
        media = mediaPlayerUtil.getNetMedia(Constants.Url.AUDIO_PLAY + name);
    }

    public void clear() {
        if (list != null) {
            list.clear();
            list = null;
        }
        media = null;
        if (mediaPlayerUtil != null) {
            mediaPlayerUtil.clearMediaPlayer();
        }
        if (handler != null) {
            handler.sendEmptyMessage(2);
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    /**
     * 查看文字
     */
    public void showText(String content) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setCancelable(false);  //先得到构造器
        // builder.setTitle("提示"); //设置标题
        builder.setMessage(content); //设置内容
//        builder.setPositiveButton("发布", new DialogInterface.OnClickListener() { //设置确定按钮
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
        builder.setNegativeButton("已阅", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

    /**
     * 调用援权接口是否可听可看
     */
    public void getAuthorized(String questionUuid, String voiceUuid, final String during, final ViewHolder viewHolder, final String tag) {
        if (QuickDoubleClickable.isDoubleClick()) {
            return;
        }
        RequestAuthorizedModel requestAuthorizedModel = new RequestAuthorizedModel();
        requestAuthorizedModel.setUuid(questionUuid);
        requestAuthorizedModel.setVoiceId(voiceUuid);
        HttpUtil.doPost(Constants.Url.AUDIO_AUTHORIZED, requestAuthorizedModel, new HttpResponse(context, AuthorizedResultModel.class) {
            @Override
            public void onResult(Object obj) {
                AuthorizedResultModel resultModel = (AuthorizedResultModel) obj;
                AuthorizedResultModel.DataBean data = resultModel.getData();
                if (data != null) {
                    String type = data.getType();
                    if ("0".equals(type)) {
                        voiceName = data.getVoiceName();
                        voiceContent = data.getVoiceText();
                        if ("voice".equals(tag)) {
                            viewHolder.relativeLayout.setBackground(context.getResources().getDrawable(R.drawable.listen_foucu));
                            if (media != null && media.isPlaying()) {
                                media.seekTo(0);
                                stopMedia();
                                viewHolder.relativeLayout.setEnabled(true);
                                viewHolder.relativeLayout.setBackground(context.getResources().getDrawable(R.drawable.listenback));
                                viewHolder.gifView.setVisibility(View.GONE);
                                viewHolder.show_iv.setVisibility(View.VISIBLE);
                            } else {
                                time = String.valueOf(during);
                                Message msg = Message.obtain();
                                msg.what = 1;
                                msg.obj = viewHolder;
                                handler.sendMessage(msg);
                                playAudio(voiceName);
                            }
                        } else if ("text".equals(tag)) {
                            showText(voiceContent);
                        }

                    } else if ("1".equals(type)) {
                        voiceName = "";
                        voiceContent = "";
                        showBuy(dataBean.getQuPrice());
                    }
                }
            }
        });
    }

    /**
     * 是否购买
     */
    public void showBuy(double price) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setCancelable(false);  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("收听/查看此问题需要支付" + price + "元"); //设置内容
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                IntentManager.goPayResultActivity(context, dataBean.getQuestion(), String.valueOf(dataBean.getQuPrice()), dataBean.getUuid(), 5);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

}

